import { isDevEnv } from './env';
import VConsole from 'vconsole';

let vConsoleInstance = null;

export const initDebugTools = () => {
  if (!isDevEnv()) return;
  
  // 创建 vConsole 实例
  vConsoleInstance = new VConsole({
    theme: 'light',
    maxLogNumber: 1000,
    onReady: () => console.log('[vConsole] 调试面板已就绪')
  });
  
  // 添加自定义面板
  vConsoleInstance.addPlugin(new VConsole.VConsolePlugin('wecode', 'We码工具', {
    onRender: (cell) => {
      cell.innerHTML = `
        <div style="padding:10px">
          <h3>We码环境信息</h3>
          <p><strong>UserAgent:</strong> ${navigator.userAgent}</p>
          <p><strong>当前时间:</strong> ${new Date().toLocaleString()}</p>
          <p><strong>HWH5 版本:</strong> ${window.HWH5?.version || '未检测到'}</p>
          <p><strong>SDK 功能:</strong> ${window.HWH5 ? Object.keys(window.HWH5).join(', ') : '无'}</p>
          
          <button id="mock-nfc-btn" style="margin-top:15px;padding:8px 12px;background:#07c160;color:white;border:none;border-radius:4px">
            模拟 NFC 数据
          </button>
        </div>
      `;
      
      // 添加模拟 NFC 按钮事件
      document.getElementById('mock-nfc-btn')?.addEventListener('click', () => {
        mockNFCEvent();
      });
    }
  }));
  
  console.log('[debug] vConsole 已初始化');
};

// 模拟 NFC 事件
export const mockNFCEvent = () => {
  if (!isDevEnv()) return;
  
  const mockData = {
    tagId: new Uint8Array([0x04, 0x5F, 0x2A, 0x9D, 0x5A, 0x91, 0x80]),
    techTypes: ["NfcA", "Ndef"],
    records: [{
      tnf: 1,
      type: 'T',
      payload: new TextEncoder().encode('模拟NFC数据: ' + new Date().toLocaleTimeString())
    }]
  };
  
  console.log('[mock] 发送模拟NFC数据:', mockData);
  
  // 触发全局事件
  const event = new CustomEvent('nfcDataReceived', { detail: mockData });
  window.dispatchEvent(event);
};

// 安全日志方法
export const safeLog = (...args) => {
  if (isDevEnv()) {
    console.log('[DEBUG]', ...args);
  }
};

// 销毁调试工具
export const destroyDebugTools = () => {
  if (vConsoleInstance) {
    vConsoleInstance.destroy();
    vConsoleInstance = null;
    console.log('[debug] vConsole 已销毁');
  }
};